package com.superbug.moi.stupiccqupt.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Message;

import com.superbug.moi.stupiccqupt.ui.fragment.SearchIdFragment;
import com.superbug.moi.stupiccqupt.util.HttpCallbackListener;
import com.superbug.moi.stupiccqupt.util.HttpUtil;
import com.superbug.moi.stupiccqupt.util.LogUtil;
import com.superbug.moi.stupiccqupt.util.ResponseCallbackListener;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyService extends Service {
    private MyBinder binder = new MyBinder();
    private Message message = new Message();
    private ResponseCallbackListener listener = null;
    private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

    public MyService() {
    }

    /**
     * 获取当前Service实例
     */
    public MyService getInstance() {
        return this;
    }

    /**
     * 给当前Service设置回调者
     */
    public void setResponseCallbackListener(ResponseCallbackListener listener) {
        this.listener = listener;
    }

    /**
     * 让bindService的活动可以获取到Service实例
     */
    public class MyBinder extends Binder {
        public MyService getMyService() {
            return getInstance();
        }
    }
    @Override
    public IBinder onBind(Intent intent) {
        final String address = intent.getStringExtra("address");
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
                    @Override
                    public void onFinish(String response) {
                        Document document = Jsoup.parse(response.toString());
                        Elements trs = document.select("tr");
                        int totalTrs = trs.size();
                        if (totalTrs > 2) {
                            for (int i = 1; i < totalTrs; i++) {
                                Elements tds = trs.get(i).select("td");
                                int totalTds = tds.size();
                                Map<String, Object> map = new HashMap<String,Object>();
                                for (int j = 0; j < totalTds; j++) {
                                    switch (j) {
                                        /**
                                         * 0：学号
                                         * 1：姓名
                                         * 2：性别
                                         * 3：班级
                                         * 4：专业
                                         * 5：院系
                                         * 6：年级
                                         */
                                        case 0:
                                            map.put("stu_id", cutNbsp(tds.get(j).html()));
                                            break;
                                        case 1:
                                            map.put("stu_name", cutNbsp(tds.get(j).html()));
                                            break;
                                        case 2:
                                            map.put("stu_sex", cutNbsp(tds.get(j).html()));
                                            break;
                                        case 3:
                                            map.put("stu_class", cutNbsp(tds.get(j).html()));
                                            break;
                                        case 4:
                                            map.put("stu_major", cutNbsp(tds.get(j).html()));
                                            break;
                                        case 5:
                                            map.put("stu_faculty", cutNbsp(tds.get(j).html()));
                                            break;
                                        case 6:
                                            map.put("stu_grade", cutNbsp(tds.get(j).html()));
                                            break;
                                    }
                                }
                                list.add(map);
                            }
                        } else {
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("error", "同学，\n1.你确定输正确了？\n2.你确定你连了内网？没有内网不能飞哦~");
                            list.add(map);
                        }

                        LogUtil.getInstance().d("TAG","service中Http请求成功，内容为：" + list.toString());
                        message.what = SearchIdFragment.SHOW_RESPONSE;
                        message.obj = list;
                        /**
                         * http解析完成，执行回调函数，将message传递过去
                         */
                        listener.onFinish(message);

                    }

                    @Override
                    public void onError(Exception e) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("error", "同学，\n1.你确定输正确了？\n2.你确定你连了内网？没有内网不能飞哦~");
                        list.add(map);
                        message.what = SearchIdFragment.SHOW_RESPONSE;
                        message.obj = list;
                    }
                });
                stopSelf();
            }
        }).start();
        LogUtil.getInstance().d("TAG", "开启了service, 传入的地址为：" + address);
        return binder;
    }

    /**
     * 为了去除html返回的烦人的 &nbsp;
     */
    private String cutNbsp(String html) {
        char [] cut;
        String temp = "";
        cut = html.toCharArray();
        for (int k = 0; k < cut.length; k ++) {
            temp += cut[k];
            if (cut[k] == ';') {
                temp = "";
            }
        }
        return temp;
    }

}
